package com.zjw.hyphenateui.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.havi.helper.ChatHelper;
import com.example.havi.ui.ChatActivity;
import com.example.havi.util.ChatSPUtil;
import com.example.havi.util.ChatToastUtil;
import com.example.havi.util.LogUtil;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.NetUtils;
import com.zjw.hyphenateui.MainApplication;
import com.zjw.hyphenateui.R;
import com.zjw.hyphenateui.helper.NotificationConstants;
import com.zjw.hyphenateui.helper.NotificationHelper;
import com.zjw.hyphenateui.widget.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.viewPager)
    NoScrollViewPager viewPager;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.unread_msg_number)
    TextView unreadMsgNumber;
    private List<Fragment> fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initMenus();
        initView();
        //根据ID消除通知
        NotificationHelper.getInstance().cancelNotification(NotificationConstants.HYPHENATE_NOTIFCATION_ID);
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());

    }


    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
            LogUtil.e("zjw_zjw","main onConnected=");
        }
        @Override
        public void onDisconnected(final int error) {
            LogUtil.e("zjw_zjw","amin onDisconnected="+error);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除
                        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("警告");
                        builder.setMessage("帐号已经被移除！！");
                        builder.setCancelable(false);
                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                startActivity(new Intent(MainActivity.this,LoginActivity.class));
                                ChatSPUtil.setString("chat_user", "");
                                ChatSPUtil.setString("chat_pwd", "");
                                finish();
                            }
                        });
                        builder.show();
                    }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("警告");
                        builder.setMessage("账号异地登录！！");
                        builder.setCancelable(false);
                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                startActivity(new Intent(MainActivity.this,LoginActivity.class));
                                ChatHelper.getInstance().loginOut();
                                ChatSPUtil.setString("chat_user", "");
                                ChatSPUtil.setString("chat_pwd", "");
                                finish();
                            }
                        });
                        builder.show();
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)){
                            ChatToastUtil.showToast(getBaseContext(),"连接不到聊天服务器");
                            //连接不到聊天服务器
                        }else{
                            //当前网络不可用，请检查网络设置
                            ChatToastUtil.showToast(getBaseContext(),"当前网络不可用，请检查网络设置");
                        }
                    }
                }
            });
        }
    }

    String[] tabNames;
    int[] tabIcons;

    private void initMenus() {
        tabNames = getResources().getStringArray(R.array.main_tabs);
        TypedArray ar = getResources().obtainTypedArray(R.array.main_tab_icons);
        int len = ar.length();
        tabIcons = new int[len];
        for (int i = 0; i < len; i++) {
            tabIcons[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
    }

    private void initView() {
        fragments = new ArrayList<>();
        fragments.add(new MessageFragment());
        fragments.add(new SearchChatFragment());
        fragments.add(new MineFragment());
        viewPager.setOffscreenPageLimit(2);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return null;
            }

        });
        //设置图标
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabNames.length; i++) {
            tabLayout.getTabAt(i).setCustomView(getTabView(tabNames[i], tabIcons[i]));
        }
    }

    public View getTabView(String tabName, int tabIcon) {
        View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.tab_layout, null);
        ImageView iv_tab = view.findViewById(R.id.iv_tab);
        TextView tv_tab = view.findViewById(R.id.tv_tab);
        iv_tab.setImageResource(tabIcon);
        tv_tab.setText(tabName);
        return view;
    }


    @Override
    protected void onResume() {
        super.onResume();
        updateUnreadLabel();    //更新消息未读数
        EMClient.getInstance().chatManager().addMessageListener(messageListener);   //添加消息接收监听
    }

    @Override
    protected void onStop() {
        super.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener); //移除消息接收监听
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            // TODO: 2018/7/5 此处应该发送通知
//            for (EMMessage message : messages) {
//                DemoHelper.getInstance().getNotifier().onNewMsg(message);
//            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            refreshUIWithMessage();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };


    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateUnreadLabel();
                //如果一级界面是会话列表 在这里调用方法更新
                ((MessageFragment)fragments.get(0)).refresh();
            }
        });
    }


    /**
     * 更新消息未读数
     */
    private void updateUnreadLabel() {
        int unreadMessageCount = EMClient.getInstance().chatManager().getUnreadMessageCount();
        if(unreadMessageCount>0){
            unreadMsgNumber.setText(unreadMessageCount+"");
            unreadMsgNumber.setVisibility(View.VISIBLE);
        }else{
            unreadMsgNumber.setVisibility(View.INVISIBLE);
        }
    }

}
